﻿using System;
using System.Linq;
using KPIS.GERP.Models.HRM;

namespace KPIS.GERP.Models.Class
{
    public static class HrmSystemControlUtil
    {
        private static HrmSystemControls Retreive(string name, string defaultValue = null)
        {
            GERPContext db = new GERPContext();
            var hrmSysCtrls = db.HrmSystemControls;
            var obj = hrmSysCtrls.FirstOrDefault(o => o.Name == name);
            if (obj == null)
            {
                db.HrmSystemControls.Add(new HrmSystemControls
                {
                    Name = name, Value = defaultValue
                });
                db.SaveChanges();
            }

            obj = hrmSysCtrls.FirstOrDefault(o => o.Name == name);
            if (obj == null)
            {
                throw new Exception("กรุณาตั้งค่า hrm_system_control[Name=" + name + "]");
            }
            else
            {
                return obj;
            }
        }

        public static TimeSpan StartWorking
        {
            get
            {
                return Retreive("start_working", "8:30").GetTimeSpan(); 
            }
        }

        public static TimeSpan EndWorking
        {
            get
            {
                return Retreive("end_working", "16:00").GetTimeSpan(); 
            }
        }

        public static TimeSpan StartWorkingAfternoon
        {
            get
            {
                return Retreive("start_working_afternoon", "13:00").GetTimeSpan(); 
            }
        }

        public static TimeSpan EndWorkingMorning
        {
            get
            {
                return Retreive("end_working_morning", "12:00").GetTimeSpan(); 
            }
        }
    }
}